/**
 * 细分数据
 */
'use strict';
define([
    '../../../../../modules/business/videoManage/base/baseView',
    '../../../../../modules/common/service',
    '../../../../../modules/common/utils'
], function(
    BaseView,
    http
) {
    function me() {
        BaseView.apply(this, arguments);
        this.init = function(idstr) {
            this.getData(idstr);
        }
        this.appendTableColumn = function(idStr,type,data,tableHeader){   //ul : append / prepend
            var self = this;
            if(data.length == 0){
                console.log("statistical data is empty!");
                return false;
            }
            var length = data[Object.keys(data)[0]].length;
            //make subdivide data
            var tableData = [];
            for(var i = 0;i<length;i++){
                var tableObj = [];
                for(var j = 0;j<tableHeader.length;j++){
                    if(-1 != $.inArray(tableHeader[j], ["todaySpent","spent","cpc","cps","salesAmount","budget","gaOrderAmount","gaCpa","gaOrderPrice"])){
                        //_formatMoney
                        tableObj.push(self._formatMoney(data[tableHeader[j]][i]));
                    }else if(-1 != $.inArray(tableHeader[j], ["ctr","purchaseR","cartR","gaCartR","gaCr"])){
                        //_formatMone
                        tableObj.push(self._formatPercent(data[tableHeader[j]][i]));
                    }else if(-1 != $.inArray(tableHeader[j], ["roi","gaCpc","gaRoi"])){
                        //_formatMoney
                        tableObj.push(data[tableHeader[j]][i].toFixed(2));
                    }else{
                        tableObj.push(data[tableHeader[j]][i]);
                    }
                }
                tableData.push(tableObj);
            }
            var startData = $('input[name=statsTimeRange-since]').val();
            var headerColumWidth = $('.treable-header').find('.sutable-col:last').css("width");
            //render table
            var _html = "";
            for(var v = 0;v<tableData.length;v++){
                var tempArr = tableData[v];
                _html += '<li class="treable-item subdivide" deep="2"><div class="treable-row-wrapper"><div class="treable-row"  deep="2">';
                _html +='<span class="sutable-col sutable-col-status" col="0" style="margin-left: 20px;"></span>' ;
                _html +='<span class="sutable-col sutable-col-name" col="1">'+new Date(startData).addDays(v).format("yyyy-MM-dd") +'</span>' ;
                _html +='<span class="sutable-col" col="2" style="width:'+headerColumWidth+'"></span>' ;
                _html +='<span class="sutable-col" col="3" style="width:'+headerColumWidth+'"></span>' ;//campain
                for(var i = 4;i<tempArr.length+4;i++){
                    _html +='<span class="sutable-col" col="'+ i +'" style="width:'+headerColumWidth+'">'+ tempArr[i-4] +'</span>';
                }
                _html +='<span class="sutable-col" col="'+(tableData[0].length + 4)+'" style="width: '+headerColumWidth+'">-</span>';
                _html +='<span class="sutable-col" col="'+(tableData[0].length + 5)+'" style="width:'+headerColumWidth+'">-</span>';
                _html +='<span class="sutable-col" col="'+(tableData[0].length + 6)+'" style="width: '+headerColumWidth+'">-</span>';
                _html +='</div></div></li>';
            }
            if(type == "adset"){
                var $parentDom = $('li[data-id='+idStr+']').find('ul.sub-layer');
                $parentDom.find('li').remove('.subdivide');
                $parentDom.prepend(_html);
            }else{
                var s$parentDom = $('li[data-id='+idStr+']').closest("li[deep=1]").find('ul.sub-layer');
                s$parentDom.find('li').remove('.subdivide');
                s$parentDom.append(_html);
            }
        }
        this.filterHeaderData = function(arr1,arr2){
            var tempArray = [];
            $.each(arr1,function(i,obj){
                if(-1 != $.inArray(obj,arr2)){
                    tempArray.push(obj);
                }
            });
            return tempArray;
        }
        this.getData = function(idStr) {
            var self = this;
            var type = idStr.split('-')[0];
            var _id = idStr.split('-')[1];
            var sessionTableHeader = window.localStorage.getItem("tableHeader").split(",");
            var _returnStatsFields =["todaySpent","spent","clicks","ctr","cpc","purchase","purchaseR","cps","salesAmount","roi","cart","cartR","gaClicks","gaCart","gaPays","gaOrderAmount","gaCartR","gaCpa","gaCpc","gaOrderPrice","gaRoi","gaCr"];
            _returnStatsFields = self.filterHeaderData(_returnStatsFields,sessionTableHeader);
            http.do("/admanage/graphbyday", {param: JSON.stringify({
                "ecReport" : true,
                "id": _id,
                "statsTimeRange": {
                    "since": $('input[name=statsTimeRange-since]').val(),
                    "until": $('input[name=statsTimeRange-until]').val()
                },
                "returnStatsFields": _returnStatsFields})
            }).then(function(res) {
                self.appendTableColumn(idStr,type,res.data,_returnStatsFields);
            }, function() {});
        }
        /**
         * { 格式金钱 }
         *
         * @method     _formatMoney
         * @param      {<type>}  argument  { description }
         */
        this._formatMoney = function(item) {
            return ((item || item == 0) ? (item == '-' ? '-' : '$ ' + kit.cent_to_dollar(item)) : '-') + '';
        }

        this._formatPercent = function(item) {
            return ((item || item == 0) ? (item == '-' ? '-' : kit.percentage(item)) : '-') + '';
        }
    };
    return me;
});
